// Copyright 2025 CCC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and

import { isString, isObject } from '@/utils/is';

// limitations under the License.
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm';

export function joinTimestamp(join: boolean, restful = false): string | object {
  if (!join) {
    return restful ? {} : '';
  }

  const now = new Date().getTime();

  if (restful) {
    return `?_t=${now}`;
  }

  return { _t: now };
}

/**
 * @description 格式化时间戳
 */
export function formatRequestDate(params: Record<string, any>) {
  if (Object.prototype.toString.call(params) === '[object Object]') {
    return;
  }

  for (const key in params) {
    if (params[key] && params[key]._isAdayjsObject) {
      params[key] = params[key].format(DATE_TIME_FORMAT);
    }

    if (isString(key)) {
      const value = params[key];

      if (value) {
        try {
          params[key] = isString(value) ? value.trim() : value;
        } catch (error: any) {
          throw new Error(error);
        }
      }
    }

    if (isObject(params[key])) {
      formatRequestDate(params[key]);
    }
  }
}
